package org.tcx.common.json;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;

public class ReflectUtil {
	public static void setFiled(final Field field, final Object instance,
			final Object value) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			public Object run() {
				try {
					if (!field.isAccessible()) {
						field.setAccessible(true);
					}
					field.set(instance, value);
					return null;
				} catch (IllegalAccessException e) {
					throw new RuntimeException("IllegalAccessException", e);
				}
			}
		});
	}
	public static void setFiled(final String fieldName, final Object instance,
			final Object value) {
		Field field;
		try {
			 field = instance.getClass().getDeclaredField(fieldName);
		} catch (SecurityException e) {
			throw new AssertionError(e);
		} catch (NoSuchFieldException e) {
			throw new AssertionError(e);
		}
		setFiled(field,instance,value);
	}
	public static Object getFiled(final Field field, final Object instance) {
		return AccessController.doPrivileged(new PrivilegedAction<Object>() {
			public Object run() {
				try {
					if (!field.isAccessible()) {
						field.setAccessible(true);
					}
					return field.get(instance);
				} catch (IllegalAccessException e) {
					throw new RuntimeException("IllegalAccessException", e);
				}
			}
		});
	}

	public static Object getFiled(String fieldName, Object instance){
		Field field;
		try {
			field = instance.getClass().getDeclaredField(fieldName);
		} catch (SecurityException e) {
			throw new AssertionError(e);
		} catch (NoSuchFieldException e) {
			throw new AssertionError(e);
		}
		return ReflectUtil.getFiled(field, instance);
	}
}
